import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'

export const useInputStringStore = defineStore('inputString', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const currentDialog = ref(null)
  const value = ref('')
  const isNumber = ref(false)

  // 计算属性
  const isValid = computed(() => {
    if (!isNumber.value) return true
    const num = parseFloat(value.value)
    return !isNaN(num) && isFinite(num)
  })

  const isPassword = computed(() => {
    const title = currentDialog.value?.title || ''
    return title.toLowerCase().includes('password') || title.includes('密码')
  })

  // 动作
  function show(titleText, defaultValue, forNumber) {
    return dialogQueue.show({
      onLoaded: () => {
        value.value = forNumber ? defaultValue.toString() : defaultValue
        isNumber.value = forNumber
        currentDialog.value = {
          title: titleText,
          defaultValue
        }
      }
    })
  }

  function confirm() {
    if (isValid.value) {
      const result = isNumber.value ? parseFloat(value.value) : value.value
      dialogQueue.hide(result)
    }
  }

  function cancel() {
    dialogQueue.hide(currentDialog.value.defaultValue)
  }

  function handleKeyPress(event) {
    if (event.key === 'Enter' && isValid.value) {
      confirm()
    }
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    title: () => currentDialog.value?.title || '',
    value,
    isNumber,
    // 计算属性
    isValid,
    isPassword,
    // 动作
    show,
    confirm,
    cancel,
    handleKeyPress,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 